<?php

namespace Siese\EntityBundle\Form\EventListener;
 
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Doctrine\ORM\EntityRepository;
 
class AddEntidadesInspeccionFieldSubscriber implements EventSubscriberInterface
{
    private $propertyPathToEntidad;
 
    public function __construct($propertyPathToEntidad)
    {
        $this->propertyPathToEntidad = $propertyPathToEntidad;
    }
 
    public static function getSubscribedEvents()
    {
        return array(
            FormEvents::PRE_SET_DATA  => 'preSetData',
            FormEvents::PRE_SUBMIT    => 'preSubmit'
        );
    }
 
    private function addEntidadesForm($form, $estado)
    {
        $formOptions = array(
            'class'         => 'SieseEntityBundle:Entidades',
            'empty_value'   => 'Seleccione una Opción',
            'label'         => 'Entidad',
            'required'      => true,
            'mapped'        => true,
            'attr'          => array(
                'class' => 'entidades_selector form-control',
            ),
            'query_builder' => function (EntityRepository $repository) use ($estado) {
            
                $qb = $repository->createQueryBuilder('ei')
                                 ->where('ei.estado = :estado')
                                 ->setParameter('estado',$estado)
                ;
                
                
                return $qb;
            }
        );
 
        $form->add($this->propertyPathToEntidad, 'entity', $formOptions);
    }
    
    
    public function preSetData(FormEvent $event)
    {
        $data = $event->getData();
        $form = $event->getForm();
 
        if (null === $data) {
            return;
        }
 
        $accessor    = PropertyAccess::createPropertyAccessor();
 
        $entidad = $accessor->getValue($data,$this->propertyPathToEntidad);
        
        $estado_id = ($entidad) ? $entidad->getEstado()->getId() : null;
 
        $this->addEntidadesForm($form, $estado_id);
    }
 
    public function preSubmit(FormEvent $event)
    {
        $data = $event->getData();
        $form = $event->getForm();
        
        $estado_id = array_key_exists('estadoEnt', $data) ? $data['estadoEnt'] : null;
        
        $this->addEntidadesForm($form, $estado_id);
    }
}
